from pyamf import flex, remoting, DecodeError, TypedObject
import pprint, string
import re

def decode_chunked(data):
    offset = 0
    encdata = ''
    newdata = ''
    offset = string.index(data, "\r\n\r\n") + 4
    encdata =data[offset:]
    try:
        while (encdata != ''):
            off = int(encdata[:string.index(encdata,"\r\n")],16)
            if off == 0:
                break
            encdata = encdata[string.index(encdata,"\r\n") + 2:]
            newdata = "%s%s" % (newdata, encdata[:off])
            encdata = encdata[off+2:]
    except:
       line = traceback.format_exc()
       print "Exception! %s" %line
    return newdata

def print_data(key, data, indent=8):
    if type(data[key]) == TypedObject:
        print "%s[TypedObject]" % (' ' * indent)
        print "%s  [alias] %s" % (' ' * indent, data[key].alias)
        print "%s  [data]" % (' ' * indent)
        for k in data[key]:
            print_data(k, data[key], indent+4)
    elif type(data[key]) == flex.ArrayCollection:
        print "%s[ArrayCollection]" % (' ' * indent)
        for k in data[key]:
            print_data(0, [k], indent+4)
    else:
        print "%s[%s] %s" % (' ' * indent, key, data[key])

def print_request(packet):
    print "<AMF Request>"
    print "  [target] %s" % packet.target
    for command_message in packet.body:
        print "  [CommandMessage]"
        print "    [clientId] %s" % command_message.clientId
        print "    [destination] %s" % command_message.destination
        print "    [messageId] %s" % command_message.messageId
        print "    [timeToLive] %s" % command_message.timeToLive
        print "    [timestamp] %s" % command_message.timestamp
        for typed_object in command_message.body:
            print "    [TypedObject]"
            print "      [alias] %s" % typed_object.alias
            print "      [data]"
            for k1 in typed_object.iterkeys():
                print_data(k1, typed_object)
    print "</AMF Request>\n"

def print_response(packet):
    print "<AMF Response>"
    print "  [status] %s" % packet.status
    command_message = packet.body
    print "  [CommandMessage]"
    print "    [clientId] %s" % command_message.clientId
    print "    [destination] %s" % command_message.destination
    print "    [messageId] %s" % command_message.messageId
    print "    [timeToLive] %s" % command_message.timeToLive
    print "    [timestamp] %s" % command_message.timestamp
    print "    [TypedObject]"
    print "      [alias] %s" % command_message.body.alias
    print "      [data]"
    for k1 in command_message.body.iterkeys():
        print_data(k1, command_message.body)
    print "</AMF Response>\n"


def print_packet(amf_packet):
    for id_packet, packet in amf_packet.iteritems():
        if (type(packet) == remoting.Response):
                print_response(packet)
        else:
            print_request(packet)

